/************************************************************************
 * The code is owned by mainframer.cn and Shang Tao
 * Without aproval of mainframer.cn and Shang Tao, removing the copyright
 * infomation is regarded as invassion of proprietary copyright
 ***********************************************************************/
package com.mr.qa.exception;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ExceptionHandler;
import org.apache.struts.config.ExceptionConfig;

import com.mr.qa.UserSession;
import com.mr.qa.UserSessionUtil;

public class StrutsExceptionHandler extends ExceptionHandler
{
    private static final Log log = LogFactory.getLog(StrutsExceptionHandler.class);
    public StrutsExceptionHandler()
    {
    }
    public ActionForward execute(Exception exception, ExceptionConfig exConfig, ActionMapping mapping,
            ActionForm formInstance, HttpServletRequest request, HttpServletResponse response) throws ServletException
    {
            QaException qaException;
            String error;
            if (exception instanceof QaException)
            {                
                qaException = (QaException)exception;
                error = exception.getMessage();
            } 
            else 
            {
                qaException = new QaException(exception);           
                error = qaException.getMessage();
            }
            UserSession us = UserSessionUtil.getUserSession(request);
            String url = request.getRequestURL().toString()+"?"+request.getQueryString();
            String referer = request.getHeader("Referer");
            String userAgent = request.getHeader("User-Agent");
            String ip = request.getRemoteAddr()+":"+request.getRemoteHost()+":"+request.getRemoteUser();
            //if(referer == null)referer = url;
            if(us == null)
                log.error(ip+","+"User-Agent="+userAgent+","+"Url="+url+","+"Referer="+referer+", Fatal Error Occured=",qaException);
            else
                log.error(ip+","+"User-Agent="+userAgent+","+"Url="+url+","+"Referer="+referer+", "+us.getUserId()+":"+us.getLoginName()+",Fatal Error Occured=",qaException);
            request.setAttribute("fatal.error", error);
            request.setAttribute("qae", qaException);
            if(exception instanceof SecurityException)
                return mapping.findForward("relogin");
            else
                return mapping.findForward("uncaughterror");
    }    
}
